package com.jeesite.modules.wx.miniapp.controller;

import com.google.common.collect.Maps;
import com.jeesite.common.config.Global;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.bis.entity.BisDispatch;
import com.jeesite.modules.bis.entity.BisSignIn;
import com.jeesite.modules.bis.entity.BisUser;
import com.jeesite.modules.bis.service.BisDispatchService;
import com.jeesite.modules.bis.service.BisSignInService;
import com.jeesite.modules.bis.service.BisUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 获取业务数据
 */
@RestController
@RequestMapping("/wx/signIn/{appid}")
public class WxBisSignInController extends BaseController {
    @Autowired
    private BisSignInService bisSignInService;
    @Autowired
    private BisUserService bisUserService;

    @PostMapping("/getTodaySignInData")
    public String getTodaySignInData(String sessionKey) {
        if (StringUtils.isBlank(sessionKey)) {
            return renderResult(Global.FALSE, "非法访问");
        }
        BisUser bisUser = bisUserService.getBySessionKey(sessionKey);
        if (bisUser == null) {
            return renderResult(Global.FALSE, "没有找到用户");
        }
        Map<String,Object> result = Maps.newHashMap();

        Integer seriesCount = bisSignInService.getSeriesCount(bisUser.getId());
        result.put("seriesCount", seriesCount);

        int totalCount = bisSignInService.getTotalCount(bisUser.getId());
        result.put("totalCount", totalCount);

        boolean todaySignState = bisSignInService.getTodaySignState(bisUser.getId());
        result.put("todaySignState", todaySignState);

        return renderResult(Global.TRUE, "成功", result);
    }

    @PostMapping("/doSignIn")
    public String doSignIn(String sessionKey) {
        if (StringUtils.isBlank(sessionKey)) {
            return renderResult(Global.FALSE, "非法访问");
        }
        BisUser bisUser = bisUserService.getBySessionKey(sessionKey);
        if (bisUser == null) {
            return renderResult(Global.FALSE, "没有找到用户");
        }
        boolean todaySignState = bisSignInService.getTodaySignState(bisUser.getId());
        if (!todaySignState) {
            BisSignIn bisSignIn = new BisSignIn();
            bisSignIn.setBisUserId(bisUser.getId());
            bisSignIn.setSignInTime(new Date());
            bisSignInService.save(bisSignIn);
        } else {
            return renderResult(Global.FALSE, "今天已经签到过了");
        }
        return renderResult(Global.TRUE, "成功");
    }

}
